package com.liukai.personalbills.service.impl;

import com.liukai.personalbills.dao.UserDao;
import com.liukai.personalbills.entity.User;
import com.liukai.personalbills.service.UserService;
import com.liukai.personalbills.util.TextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public String login(User user) {

        String result = TextUtil.LOGIN_FAIL_NO_USER;

        User user1 = userDao.findByUserName(user.getUsername());
        // 该用户在数据库不存在，登陆失败
        if(user1 == null){
            result = TextUtil.LOGIN_FAIL_NO_USER;
            return result;
        }
        // 用户存在，密码一致，登陆成功
        if(user1.getPassword().equals(user.getPassword())){
            result = TextUtil.LOGIN_SUCCESS;
            return result;
        }else{ // 用户存在，密码不一致，登陆失败
            result = TextUtil.LOGIN_FAIL_ERROR_PASS;
            return result;
        }
    }

    @Override
    public String register(User user) {

        String result = TextUtil.REGISTER_FAIL_USER_EXIST;

        User user1 = userDao.findByUserName(user.getUsername());
        // 用户存在，注册失败
        System.out.println(user1);
        if (user1 != null){
            return result;
        }else{ // 该用户不存在注册成功
            userDao.save(user);
            result = TextUtil.REGISTER_SUCCESS;
            return result;
        }
    }


    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,
            propagation = Propagation.REQUIRED,
            timeout = -1, //默认不设置超时
            readOnly = false,
            rollbackFor = {RuntimeException.class}) //出现运行时异常回会滚
    public String update(User user) {

        String result = TextUtil.UPDATE_FAIL;
        userDao.update(user);
        User user1 = userDao.findByUserName(user.getUsername());
        if(user1.getPassword().equals(user.getPassword())){
            result = TextUtil.UPDATE_FAIL;
//            throw new RuntimeException("异常");
        }else{
            result = TextUtil.UPDATE_SUCCESS;
        }
        return result;
    }
}
